package com.qcby.front.service.impl;

import com.qcby.framwork.utils.ResponseResult;
import com.qcby.front.model.LoginUser;
import com.qcby.front.model.SysUser;
import com.qcby.front.service.BlogLoginService;
import com.qcby.front.utils.JwtUtil;
import com.qcby.front.utils.RedisCache;
import com.qcby.front.vo.BlogUserLoginVo;
import com.qcby.front.vo.UserInfoVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.Objects;
@Service
public class BlogLoginServiceImpl implements BlogLoginService {
    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private RedisCache redisCache;

    @Override
    public ResponseResult login(SysUser user){
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user.getUserName(),user.getPassword());
        Authentication authenticate =  authenticationManager.authenticate(authenticationToken);
        //判断是否认证通过
        if(Objects.isNull(authenticate)){
            throw  new RuntimeException("用户名或密码错误");
        }

        //获取userId 生成 token
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        String userId = loginUser.getUser().getId().toString();
        String jwt = JwtUtil.createJWT(userId);

        //把用户信息存入redis
         redisCache.setCacheObject("bloglogin:"+userId,loginUser);

        //把token和userinfo 封装 返回
        //把user转换为 userinfoVo
        UserInfoVo userInfoVo = new UserInfoVo();
        BeanUtils.copyProperties(loginUser.getUser(), userInfoVo);
        BlogUserLoginVo vo = new BlogUserLoginVo(jwt,userInfoVo);
        return  ResponseResult.okResult(vo);
    }

    @Override
    public ResponseResult logout() {
//获取token 解析获取userid
        Authentication authentication =
                SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
//获取userid
        Long userId = loginUser.getUser().getId();
//删除redis中的用户信息
        redisCache.deleteObject("bloglogin:"+userId);
        return ResponseResult.okResult();
    }
}
